//
//  FeedView.swift
//  Twitter
//
//  Created by Hoa.wang on 2022/3/30.
//

import SwiftUI
import ParseSwift

let messageQuery = Message.query("uid" == "Qz9R1nJCSw")

struct FeedView: View {
    
    @State private var showNewTweetView = false
    @ObservedObject var viewModel = FeedViewModel()
    
    @MainActor
    @StateObject var subscription = messageQuery.subscribe!

    init() {
        let query = Message.query()
        //: This is how you subscribe to your created query using callbacks.
        let subscription = query.subscribeCallback!

        //: This is how you receive notifications about the success
        //: of your subscription.
        subscription.handleSubscribe { subscribedQuery, isNew in

            //: You can check this subscription is for this query
            if isNew {
                print("Successfully subscribed to new query \(subscribedQuery)")
            } else {
                print("Successfully updated subscription to new query \(subscribedQuery)")
            }
        }

        //: This is how you register to receive notificaitons of events related to your LiveQuery.
        subscription.handleEvent { _, event in
            switch event {

            case .entered(let object):
                print("Entered: \(object)")
            case .left(let object):
                print("Left: \(object)")
            case .created(let object):
                print("Created: \(object)")
            case .updated(let object):
                print("Updated: \(object)")
            case .deleted(let object):
                print("Deleted: \(object)")
            }
        }

        //: Now go to your dashboard, go to the GameScore table and add, update or remove rows.
        //: You should receive notifications for each.
        //: This is how you register to receive notificaitons about being unsubscribed.
        subscription.handleUnsubscribe { query in
            print("Unsubscribed from \(query)")
        }

        //: To unsubscribe from your query.
        do {
            try query.unsubscribe()
        } catch {
            print(error)
        }
    }
    
    var body: some View {
        ZStack(alignment: .bottomTrailing) {
            ScrollView {
                
                
                if subscription.subscribed != nil {
                    Text("Subscribed to query!")
                } else if subscription.unsubscribed != nil {
                    Text("Unsubscribed from query!")
                } else if let event = subscription.event {
                    
                    //: This is how you register to receive notificaitons of events related to your LiveQuery.
                    switch event.event {
                        
                    case .entered(let object):
                        Text("Entered with points: \(object.content ?? "")")
                    case .left(let object):
                        Text("Left with points: \(object.content ?? "")")
                    case .created(let object):
                        Text("Created with points: \(object.content ?? "")")
                    case .updated(let object):
                        Text("Updated with points: \(object.content ?? "")")
                    case .deleted(let object):
                        Text("Deleted with points: \(object.content ?? "")")
                    }
                } else {
                    Text("Not subscribed to a query")
                }
                
                LazyVStack {
                    ForEach(viewModel.tweets) { tweet in
                        TweetRowView(tweet: tweet)
                            .padding()
                    }
                }
            }
            
            Button {
                showNewTweetView.toggle()
            } label: {
                Image(systemName: "pencil")
                    .resizable()
                    .renderingMode(.template)
                    .frame(width: 28, height: 28)
                    .padding()
            }
            .background(Color(.systemBlue))
            .foregroundColor(.white)
            .clipShape(Circle())
            .padding()
            .fullScreenCover(isPresented: $showNewTweetView, onDismiss: {
                viewModel.fetchTweets()
            }) {
                NewTweetView()
            }
        }
        .navigationBarTitleDisplayMode(.inline)
        .refreshable {
            viewModel.fetchTweets()
        }
    }
}

struct FeedView_Previews: PreviewProvider {
    static var previews: some View {
        FeedView()
    }
}



